import React, { Component, PureComponent } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  Image,
  FlatList,
  StyleSheet,
} from 'react-native';
import { SafeAreaView } from 'react-navigation';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { get, map } from 'lodash';
import { LoadingProgramModule } from 'react-native-cgws-support';

import { DialogAlert, Nomore } from '../component';

import {
  ic_telephone_white,
  ic_message_white,
  ic_short_message_white,
} from '../assets';

import { fetchData, toggleErrorInfo, toggleOverlayContainer } from '../actions';
import { getColors } from '../theme';
import { ic_tips, ic_shares } from '../assets';
import {
  api,
  RiskRatingEnum,
  AccountStatusEnum,
  widthScale,
} from '../constants';
import {
  ConvertUtils,
  LinkingUtils,
  RNJumpUtils,
  scaleSizeW,
  scaleSizeH,
  scaleSizeFont,
} from '../utils';

function sendMessage(phone, toggleErrorInfo) {
  LinkingUtils.sendMessage(phone, err => {
    toggleErrorInfo && toggleErrorInfo({ visible: true, text: err });
  });
}

function makeACall(phone, toggleErrorInfo) {
  LinkingUtils.makeACall(phone, err => {
    toggleErrorInfo && toggleErrorInfo({ visible: true, text: err });
  });
}

const Top = props => {
  let { toggleErrorInfo } = props;
  let customerInfo = get(props, 'customerInfo', {});
  let { name, customerId, phone, imId } = customerInfo;

  return (
    <View
      style={{
        height: 94,
        backgroundColor: getColors().base_oc_11,
        flexDirection: 'row',
        paddingHorizontal: 16,
        paddingVertical: 16,
        borderTopWidth: 2,
        borderTopColor: getColors().base_lc_1,
      }}
    >
      {/* <Image
        source={ic_test}
        style={{ width: 60, height: 60, borderRadius: 4, marginRight: 12 }}
      /> */}
      <View style={{ flex: 1 }}>
        <View>
          <Text
            style={{
              fontSize: 19,
              color: getColors().base_fc_5,
              lineHeight: 30,
            }}
          >
            {name}
          </Text>
          <Image />
        </View>
        <View
          style={{
            height: 30,
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <Text style={{ fontSize: 13, color: getColors().base_fc_6 }}>
            {customerId}
          </Text>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
            }}
          >
            {!!imId && (
              <TouchableOpacity
                style={{
                  width: 30,
                  height: 30,
                  borderRadius: 30,
                  marginRight: 16,
                  backgroundColor: getColors().base_oc_27,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
                onPress={RNJumpUtils.jumpToImPage.bind(null, imId)}
              >
                <Image source={ic_message_white} />
              </TouchableOpacity>
            )}
            <TouchableOpacity
              style={{
                width: 30,
                height: 30,
                borderRadius: 30,
                marginRight: 16,
                backgroundColor: getColors().base_oc_27,
                justifyContent: 'center',
                alignItems: 'center',
              }}
              onPress={sendMessage.bind(null, phone, toggleErrorInfo)}
            >
              <Image source={ic_short_message_white} />
            </TouchableOpacity>
            <TouchableOpacity
              style={{
                width: 30,
                height: 30,
                borderRadius: 30,
                backgroundColor: getColors().base_oc_27,
                justifyContent: 'center',
                alignItems: 'center',
              }}
              onPress={makeACall.bind(null, phone, toggleErrorInfo)}
            >
              <Image source={ic_telephone_white} />
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </View>
  );
};

class Overview extends PureComponent {
  constructor(props) {
    super(props);
    let customerInfo = props.customerInfo;
    let customerAsset = this.assembleCustomerAssetInfo(customerInfo);

    this.state = {
      customerId: get(this, ['props', 'customerId'], ''),
      customerInfo,
      customerAsset,
      customerAccountStatusList: [],
    };
  }

  componentDidMount() {
    this._loadData();
  }

  // 当从原生跳转到小程序时，指定跳转到客户详情页时，需要通过props改变来驱动页面刷新
  componentWillReceiveProps(nextProps) {
    let customerInfo = nextProps.customerInfo;
    if (customerInfo !== this.props.customerInfo) {
      let customerAsset = this.assembleCustomerAssetInfo(customerInfo);
      this.setState({ customerAsset, customerInfo });
    }
  }

  // 根据客户基本信息组装客户资产信息
  assembleCustomerAssetInfo(customerInfo) {
    let info = [
      {
        name: '总资产',
        value: ConvertUtils.convertNumToStrWithUnitConversion(
          get(customerInfo, 'assetTotal', 0)
        ),
      },
      {
        name: '可用资产',
        value: ConvertUtils.convertNumToStrWithUnitConversion(
          get(customerInfo, 'capitalMoney', 0)
        ),
      },
      {
        name: '流通市值',
        value: ConvertUtils.convertNumToStrWithUnitConversion(
          get(customerInfo, 'marketValueTotal', 0)
        ),
      },
      {
        name: '佣金率',
        value: (1000 * get(customerInfo, 'commissionRate', 0)).toFixed(2) + '‰',
      },
      {
        name: '产品市值',
        value: ConvertUtils.convertNumToStrWithUnitConversion(
          get(customerInfo, 'productTotal', 0)
        ),
      },
      // {
      //   name: '收入贡献',
      //   value: ConvertUtils.convertNumToStrWithUnitConversion(
      //     get(customerInfo, 'incomeContribution', 0)
      //   ),
      // },
    ];

    return info;
  }

  _loadData = () => {
    // 客户状态
    this._fetchCustomerAccountStatus();
  };

  // 获取客户账号状态信息
  _fetchCustomerAccountStatus = () => {
    let { fetchData } = this.props;
    let { customerId } = this.state;

    const data = { customerId };
    fetchData({
      path: api.customerAccountStatus,
      method: 'post',
      body: {
        data,
      },
      callback: res => {
        let customerAccountStatusList = map(get(res, 'items', []), item1 => ({
          accountName: get(item1, 'accountName', ''),
          status: get(item1, 'status', ''),
          details: map(
            get(item1, 'details'),
            item2 => ({
              match: get(item2, 'match', false),
              name: get(item2, 'name', ''),
            }),
            []
          ),
        }));

        this.setState({
          customerAccountStatusList,
        });
      },
      errCallback: err => {
        console.log(err);
      },
    });
  };

  // 渲染客户财产信息
  renderCustomerAssertInfo(customerAsset) {
    if (customerAsset.length === 0) return null;
    return (
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          flexWrap: 'wrap',
          paddingBottom: 17,
          borderBottomWidth: 1,
          borderBottomColor: getColors().base_lc_1,
        }}
      >
        {map(customerAsset, (item, index) => (
          <View
            key={index}
            style={{
              marginTop: 10,
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: 150 * widthScale,
            }}
          >
            {item.name &&
              this.props.renderItemWithTips &&
              this.props.renderItemWithTips(item.name)}
            <Text
              style={{
                fontSize: 15,
                color: getColors().base_fc_5,
              }}
            >
              {item.value}
            </Text>
          </View>
        ))}
      </View>
    );
  }

  // 渲染客户风险评级
  renderRiskLevelInfo(riskRating, riskRatingDate) {
    return (
      <View style={{ alignSelf: 'stretch' }}>
        <Text
          style={{
            color: getColors().base_fc_6,
            marginTop: 17,
            fontSize: 15,
          }}
        >
          风险评测
        </Text>
        <View
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            borderBottomColor: getColors().base_lc_1,
            marginTop: 25,
            borderBottomWidth: 1,
            paddingBottom: 15,
          }}
        >
          <Text
            style={{
              fontSize: 15,
              color: getColors().base_fc_5,
              marginRight: 10,
            }}
          >
            {riskRating || '无评级'}
          </Text>
          {riskRating && (
            <Text style={{ fontSize: 15, color: getColors().base_fc_5 }}>
              {`有效期 ${riskRatingDate}`}
            </Text>
          )}
        </View>
      </View>
    );
  }

  // 渲染账户状态
  renderAccountStatus(list) {
    return (
      <View style={{ alignSelf: 'stretch' }}>
        <Text
          style={{
            color: getColors().base_fc_6,
            marginTop: 17,
            fontSize: 15,
          }}
        >
          账户状态
        </Text>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            flexWrap: 'wrap',
            borderBottomColor: getColors().base_lc_1,
            borderBottomWidth: 1,
            marginTop: 15,
            paddingBottom: 17,
          }}
        >
          {map(list, (item, index) => {
            let status = item.status;
            let color = getColors().base_fc_5;
            if (status === 'UNOPEN') {
              color = getColors().base_fc_7;
            } else if (status === 'INCONFORMITY') {
              color = getColors().base_fc_2;
            }

            return (
              <View
                key={index}
                style={{
                  flexDirection: 'row',
                  justifyContent: 'space-between',
                  width: 130 * widthScale,
                  marginTop: 10,
                }}
              >
                <Text style={{ fontSize: 15, color: getColors().base_fc_5 }}>
                  {item.accountName}
                </Text>
                <Text style={{ fontSize: 15, color }}>
                  {AccountStatusEnum[status]}
                </Text>
              </View>
            );
          })}
        </View>
      </View>
    );
  }

  // 渲染单条客户所属的信息
  renderCustomerRelationshipItem(type, name) {
    if (!name) return null;
    return (
      <View flexDirection="row" style={{ marginBottom: 10 }}>
        <Text style={{ width: 95, fontSize: 15, color: getColors().base_fc_5 }}>
          {type}
        </Text>
        <Text style={{ fontSize: 15, color: getColors().base_fc_5 }}>
          {name}
        </Text>
      </View>
    );
  }

  // 渲染客户所属信息
  renderCustomerRelationship(department, manager, agent, investmentConsultant) {
    return (
      <View>
        <Text
          style={{
            color: getColors().base_fc_6,
            paddingTop: 15,
            paddingBottom: 22,
            fontSize: 15,
          }}
        >
          客户归属
        </Text>
        {this.renderCustomerRelationshipItem('所属营业部', department)}
        {this.renderCustomerRelationshipItem('客户经理', manager)}
        {this.renderCustomerRelationshipItem('经纪人', agent)}
        {this.renderCustomerRelationshipItem('投资顾问', investmentConsultant)}
      </View>
    );
  }

  render() {
    let { visible } = this.props;
    if (!visible) return null;

    let { customerAsset, customerInfo, customerAccountStatusList } = this.state;
    let riskRating = RiskRatingEnum[customerInfo.riskRating];
    let riskRatingDate = ConvertUtils.convertDateToYearMonthDate(
      customerInfo.riskRatingDate
    );
    let department = get(customerInfo, 'department', undefined);
    let manager = get(customerInfo, 'manager', undefined);
    let agent = get(customerInfo, 'agent', undefined);
    let investmentConsultant = get(
      customerInfo,
      'investmentConsultant',
      undefined
    );

    return (
      <ScrollView
        contentContainerStyle={{
          backgroundColor: getColors().base_oc_11,
          paddingTop: 7,
          paddingBottom: 47,
          paddingHorizontal: 16,
        }}
      >
        {this.renderCustomerAssertInfo(customerAsset)}
        {this.renderRiskLevelInfo(riskRating, riskRatingDate)}
        {this.renderAccountStatus(customerAccountStatusList)}
        {this.renderCustomerRelationship(
          department,
          manager,
          agent,
          investmentConsultant
        )}
      </ScrollView>
    );
  }
}

const ExchangeInfo = props => {
  let { data, renderItemWithTips } = props;
  if (!data || data.length === 0) return null;

  return (
    <View
      style={{
        flexDirection: 'column',
        paddingTop: 13,
        paddingHorizontal: 16,
        backgroundColor: getColors().base_oc_11,
      }}
    >
      <View
        style={{
          flexWrap: 'wrap',
          flexDirection: 'row',
          justifyContent: 'space-between',
        }}
      >
        {map(data, (item, index) => (
          <View
            key={index}
            style={{
              marginTop: 10,
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: 150 * widthScale,
            }}
          >
            {item.name && renderItemWithTips && renderItemWithTips(item.name)}
            <Text
              style={{
                fontSize: 15,
                color:
                  (item.value.indexOf('+') !== -1 && getColors().base_fc_1) ||
                  (item.value.indexOf('-') !== -1 && getColors().base_fc_3) ||
                  getColors().base_fc_5,
              }}
            >
              {item.value}
            </Text>
          </View>
        ))}
      </View>
      <View
        style={{
          marginTop: 17,
          alignSelf: 'stretch',
          height: 1,
          backgroundColor: getColors().base_lc_1,
        }}
      />
    </View>
  );
};

const PositionHeader = props => {
  return (
    <View
      style={{
        flexDirection: 'row',
        height: 36,
        alignItems: 'center',
        paddingHorizontal: 16,
      }}
    >
      <Text
        style={{
          flex: 1,
          fontSize: 15,
          color: getColors().base_fc_6,
          lineHeight: 36,
        }}
      >
        证券
      </Text>
      <Text
        style={{
          flex: 1,
          textAlign: 'right',
          fontSize: 15,
          color: getColors().base_fc_6,
          lineHeight: 36,
        }}
      >
        盈亏
      </Text>
      <Text
        style={{
          flex: 1,
          textAlign: 'right',
          fontSize: 15,
          color: getColors().base_fc_6,
          lineHeight: 36,
        }}
      >
        持仓/市值
      </Text>
      <Text
        style={{
          flex: 1,
          textAlign: 'right',
          fontSize: 15,
          color: getColors().base_fc_6,
          lineHeight: 36,
        }}
      >
        成本/现价
      </Text>
    </View>
  );
};

const PositionItem = props => {
  let { data } = props;
  if (!data) return null;

  let color =
    (data.profitLoss.indexOf('+') !== -1 && getColors().base_fc_1) ||
    (data.profitLoss.indexOf('-') !== -1 && getColors().base_fc_3) ||
    getColors().base_fc_5;

  return (
    <View
      style={{
        flexDirection: 'row',
        marginVertical: 10,
        paddingHorizontal: 16,
      }}
    >
      <View style={{ flex: 1, flexDirection: 'column' }}>
        <Text
          style={{
            fontSize: 15,
            color: getColors().base_fc_5,
          }}
        >
          {data.name}
        </Text>
        <Text
          style={{
            marginTop: 6,
            fontSize: 13,
            color: getColors().base_fc_6,
          }}
        >
          {data.code}
        </Text>
      </View>
      <View
        style={{
          flex: 1,
          flexDirection: 'column',
          justifyContent: 'flex-end',
        }}
      >
        <Text
          style={{
            textAlign: 'right',
            fontSize: 15,
            color,
          }}
        >
          {data.profitLoss}
        </Text>
        <Text
          style={{
            textAlign: 'right',
            fontSize: 13,
            color,
          }}
        >
          {data.profitLossRate}
        </Text>
      </View>
      <View
        style={{
          flex: 1,
          flexDirection: 'column',
          justifyContent: 'flex-end',
        }}
      >
        <Text
          style={{
            textAlign: 'right',
            fontSize: 15,
            color,
          }}
        >
          {data.hold}
        </Text>
        <Text
          style={{
            textAlign: 'right',
            fontSize: 13,
            color,
          }}
        >
          {data.marketValue}
        </Text>
      </View>
      <View
        style={{
          flex: 1,
          flexDirection: 'column',
          justifyContent: 'flex-end',
        }}
      >
        <Text
          style={{
            textAlign: 'right',
            fontSize: 15,
            color,
          }}
        >
          {data.cost}
        </Text>
        <Text
          style={{
            textAlign: 'right',
            fontSize: 13,
            color,
          }}
        >
          {data.price}
        </Text>
      </View>
    </View>
  );
};

const _renderItemSeparatorComponent = () => (
  <View
    style={{
      flex: 1,
      height: 1,
      marginHorizontal: 4,
      backgroundColor: getColors().base_oc_10,
    }}
  />
);

const Positions = props => {
  let { data } = props;

  return (
    <View
      style={{
        flexDirection: 'column',
        backgroundColor: getColors().base_oc_11,
        paddingTop: 17,
      }}
    >
      <PositionHeader />
      <FlatList
        scrollEnabled={false}
        contentStyle={{ flex: 1 }}
        data={data}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item, index }) => (
          <PositionItem key={index} data={item} />
        )}
        ItemSeparatorComponent={_renderItemSeparatorComponent}
      />
    </View>
  );
};

const OptionPositionHeader = props => {
  return (
    <View
      style={{
        flexDirection: 'row',
        height: 36,
        alignItems: 'center',
        paddingHorizontal: 16,
      }}
    >
      <Text
        style={{
          flex: 1,
          fontSize: 15,
          color: getColors().base_fc_6,
          lineHeight: 36,
        }}
      >
        合约
      </Text>
      <Text
        style={{
          flex: 1,
          textAlign: 'right',
          fontSize: 15,
          color: getColors().base_fc_6,
          lineHeight: 36,
        }}
      >
        类型/方向
      </Text>
      <Text
        style={{
          flex: 1,
          textAlign: 'right',
          fontSize: 15,
          color: getColors().base_fc_6,
          lineHeight: 36,
        }}
      >
        数量/市值
      </Text>
      <Text
        style={{
          flex: 1,
          textAlign: 'right',
          fontSize: 15,
          color: getColors().base_fc_6,
          lineHeight: 36,
        }}
      >
        成本/盈亏
      </Text>
    </View>
  );
};

const OptionPositionItem = props => {
  let { data } = props;
  if (!data) return null;

  let color =
    (data.profitLoss.indexOf('+') !== -1 && getColors().base_fc_1) ||
    (data.profitLoss.indexOf('-') !== -1 && getColors().base_fc_3) ||
    getColors().base_fc_5;

  return (
    <View
      style={{
        flexDirection: 'row',
        marginVertical: 10,
        paddingHorizontal: 16,
      }}
    >
      <View style={{ flex: 1, flexDirection: 'column' }}>
        <Text
          style={{
            fontSize: 15,
            color: getColors().base_fc_5,
          }}
        >
          {data.name}
        </Text>
        <Text
          style={{
            marginTop: 6,
            fontSize: 13,
            color: getColors().base_fc_6,
          }}
        >
          {data.contract}
        </Text>
      </View>
      <View
        style={{
          flex: 1,
          flexDirection: 'column',
          justifyContent: 'flex-end',
        }}
      >
        <Text
          style={{
            textAlign: 'right',
            fontSize: 15,
            color,
          }}
        >
          {data.type}
        </Text>
        <Text
          style={{
            textAlign: 'right',
            fontSize: 13,
            color,
          }}
        >
          {data.direction}
        </Text>
      </View>
      <View
        style={{
          flex: 1,
          flexDirection: 'column',
          justifyContent: 'flex-end',
        }}
      >
        <Text
          style={{
            textAlign: 'right',
            fontSize: 15,
            color,
          }}
        >
          {data.hold}
        </Text>
        <Text
          style={{
            textAlign: 'right',
            fontSize: 13,
            color,
          }}
        >
          {data.marketValue}
        </Text>
      </View>
      <View
        style={{
          flex: 1,
          flexDirection: 'column',
          justifyContent: 'flex-end',
        }}
      >
        <Text
          style={{
            textAlign: 'right',
            fontSize: 15,
            color,
          }}
        >
          {data.cost}
        </Text>
        <Text
          style={{
            textAlign: 'right',
            fontSize: 13,
            color,
          }}
        >
          {data.profitLoss}
        </Text>
      </View>
    </View>
  );
};

const OptionPositions = props => {
  let { data } = props;

  return (
    <View
      style={{
        flexDirection: 'column',
        backgroundColor: getColors().base_oc_11,
        paddingTop: 17,
      }}
    >
      <OptionPositionHeader />
      <FlatList
        scrollEnabled={false}
        contentStyle={{ flex: 1 }}
        data={data}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item, index }) => (
          <OptionPositionItem key={index} data={item} />
        )}
        ItemSeparatorComponent={_renderItemSeparatorComponent}
      />
    </View>
  );
};

class NormalExchange extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    this._loadData();
  }

  _loadData = () => {
    this._fetchCustomerNormalExchange();
    this._fetchCustomerNormalPositions();
  };

  // 获取客户普通交易信息
  _fetchCustomerNormalExchange = () => {
    let { customerId, fetchData } = this.props;

    const data = { customerId };
    fetchData({
      path: api.customerNormalExchange,
      method: 'post',
      body: {
        data,
      },
      callback: res => {
        let normalExchange = [];
        let assetTotal = get(res, 'assetTotal', 0);
        normalExchange.push({
          name: '总资产',
          value: ConvertUtils.convertNumToStrWithUnitConversion(assetTotal),
        });

        let marketValueTotal = get(res, 'marketValueTotal', 0);
        normalExchange.push({
          name: '流通市值',
          value: ConvertUtils.convertNumToStrWithUnitConversion(
            marketValueTotal
          ),
        });

        let capitalMoney = get(res, 'capitalMoney', 0);
        normalExchange.push({
          name: '可用资产',
          value: ConvertUtils.convertNumToStrWithUnitConversion(capitalMoney),
        });

        normalExchange.push({
          name: '佣金率',
          value: (1000 * get(res, 'commissionRate', 0)).toFixed(2) + '‰',
        });

        let profitLoss = ConvertUtils.convertNumToStrWithUnitConversion(
          get(res, 'profitLoss', 0)
        );

        profitLoss = ConvertUtils.convertNumToStrWithSignSymbol(profitLoss);

        normalExchange.push({
          name: '浮动盈亏',
          value: profitLoss,
        });

        this.setState({
          normalExchange,
        });
      },
      errCallback: err => {
        console.log(err);
      },
    });
  };

  // 获取客户普通交易持仓信息
  _fetchCustomerNormalPositions = () => {
    let { fetchData, customerId } = this.props;

    const data = { customerId };
    fetchData({
      path: api.customerNormalPositions,
      method: 'post',
      body: {
        data,
      },
      callback: res => {
        let items = get(res, 'items', []);
        let normalPositions = map(items, item => {
          let normalPosition = {
            code: get(item, 'code', ''),
            available: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'available', 0)
            ),
            cost: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'cost', 0)
            ),
            hold: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'hold', 0)
            ),
            marketValue: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'marketValueTotal', 0)
            ),
            name: get(item, 'name', ''),
            price: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'price', 0)
            ),
          };

          let profitLossRate = 100 * get(item, 'profitLossRate', 0);
          let profitLoss = ConvertUtils.convertNumToStrWithUnitConversion(
            get(item, 'profitLoss', 0)
          );

          normalPosition.profitLoss = ConvertUtils.convertNumToStrWithSignSymbol(
            profitLoss
          );
          normalPosition.profitLossRate =
            ConvertUtils.convertNumToStrWithSignSymbol(profitLossRate) + '%';

          return normalPosition;
        });

        this.setState({
          normalPositions,
        });
      },
      errCallback: err => {
        console.log(err);
      },
    });
  };

  render() {
    let { visible, renderItemWithTips } = this.props;
    if (!visible) return null;

    let { normalExchange, normalPositions } = this.state;

    return (
      <ScrollView
        style={{
          flex: 1,
          backgroundColor: getColors().base_oc_10,
        }}
        contentContainerStyle={{
          backgroundColor: getColors().base_oc_10,
        }}
      >
        <ExchangeInfo
          data={normalExchange}
          renderItemWithTips={renderItemWithTips}
        />
        <Positions data={normalPositions} />
        <Nomore />
      </ScrollView>
    );
  }
}

class CreditExchange extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    this._loadData();
  }

  _loadData = () => {
    this._fetchCustomerCreditExchange();
    this._fetchCustomerCreditPositions();
  };

  // 获取客户信用交易信息
  _fetchCustomerCreditExchange = () => {
    let { customerId, fetchData } = this.props;

    const data = { customerId };
    fetchData({
      path: api.customerCreditExchange,
      method: 'post',
      body: {
        data,
      },
      callback: res => {
        let creditExchange = [];
        let assetTotal = get(res, 'assetTotal', 0);
        creditExchange.push({
          name: '总资产',
          value: ConvertUtils.convertNumToStrWithUnitConversion(assetTotal),
        });

        let assetNet = get(res, 'assetNet', 0);
        creditExchange.push({
          name: '净资产',
          value: ConvertUtils.convertNumToStrWithUnitConversion(assetNet),
        });

        let marketValueTotal = get(res, 'marketValueTotal', 0);
        creditExchange.push({
          name: '流通市值',
          value: ConvertUtils.convertNumToStrWithUnitConversion(
            marketValueTotal
          ),
        });

        let debtTotal = get(res, 'debtTotal', 0);
        creditExchange.push({
          name: '负债总额',
          value: ConvertUtils.convertNumToStrWithUnitConversion(debtTotal),
        });

        let depositAvailable = get(res, 'depositAvailable', 0);
        creditExchange.push({
          name: '可用保证金',
          value: ConvertUtils.convertNumToStrWithUnitConversion(
            depositAvailable
          ),
        });

        let capitalMoney = get(res, 'capitalMoney', 0);
        creditExchange.push({
          name: '可用资产',
          value: ConvertUtils.convertNumToStrWithUnitConversion(capitalMoney),
        });

        // let financingAccrued = get(res, 'financingAccrued', 0);
        // creditExchange.push({
        //   name: '应付融资款',
        //   value: ConvertUtils.convertNumToStrWithUnitConversion(
        //     financingAccrued
        //   ),
        // });

        // let stockLoanAccrued = get(res, 'stockLoanAccrued', 0);
        // creditExchange.push({
        //   name: '应付融券值',
        //   value: ConvertUtils.convertNumToStrWithUnitConversion(
        //     stockLoanAccrued
        //   ),
        // });

        // let financingCredit = get(res, 'financingCredit', 0);
        // creditExchange.push({
        //   name: '融资授信',
        //   value: ConvertUtils.convertNumToStrWithUnitConversion(
        //     financingCredit
        //   ),
        // });

        let financingAvailable = get(res, 'financingAvailable', 0);
        creditExchange.push({
          name: '融资可用',
          value: ConvertUtils.convertNumToStrWithUnitConversion(
            financingAvailable
          ),
        });

        // let stockLoanCredit = get(res, 'stockLoanCredit', 0);
        // creditExchange.push({
        //   name: '融券授信',
        //   value: ConvertUtils.convertNumToStrWithUnitConversion(
        //     stockLoanCredit
        //   ),
        // });

        let stockLoanAvailable = get(res, 'stockLoanAvailable', 0);
        creditExchange.push({
          name: '融券可用',
          value: ConvertUtils.convertNumToStrWithUnitConversion(
            stockLoanAvailable
          ),
        });

        let financingDebt = get(res, 'financingDebt', 0);
        creditExchange.push({
          name: '融资负债',
          value: ConvertUtils.convertNumToStrWithUnitConversion(financingDebt),
        });

        let stockLoanDebt = get(res, 'stockLoanDebt', 0);
        creditExchange.push({
          name: '融券负债',
          value: ConvertUtils.convertNumToStrWithUnitConversion(stockLoanDebt),
        });

        let interestDebt = get(res, 'interestDebt', 0);
        creditExchange.push({
          name: '利息负债',
          value: ConvertUtils.convertNumToStrWithUnitConversion(interestDebt),
        });

        creditExchange.push({
          name: '担保比例',
          value: (100 * get(res, 'collateralRatio', 0)).toFixed(2) + '%',
        });

        let profitLoss = ConvertUtils.convertNumToStrWithUnitConversion(
          get(res, 'profitLoss', 0)
        );
        profitLoss = ConvertUtils.convertNumToStrWithSignSymbol(profitLoss);

        creditExchange.push({
          name: '浮动盈亏',
          value: profitLoss,
        });

        this.setState({
          creditExchange,
        });
      },
      errCallback: err => {
        console.log(err);
      },
    });
  };

  // 获取客户信用交易持仓信息
  _fetchCustomerCreditPositions = () => {
    let { customerId, fetchData } = this.props;

    const data = { customerId };
    fetchData({
      path: api.customerCreditPositions,
      method: 'post',
      body: {
        data,
      },
      callback: res => {
        let items = get(res, 'items', []);
        let creditPositions = map(items, item => {
          let creditPosition = {
            code: get(item, 'code', ''),
            available: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'available', 0)
            ),
            cost: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'cost', 0)
            ),
            hold: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'hold', 0)
            ),
            marketValue: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'marketValueTotal', 0)
            ),
            name: get(item, 'name', ''),
            price: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'price', 0)
            ),
          };

          let profitLossRate = 100 * get(item, 'profitLossRate', 0);
          let profitLoss = ConvertUtils.convertNumToStrWithUnitConversion(
            get(item, 'profitLoss', 0)
          );

          creditPosition.profitLoss = ConvertUtils.convertNumToStrWithSignSymbol(
            profitLoss
          );
          creditPosition.profitLossRate =
            ConvertUtils.convertNumToStrWithSignSymbol(profitLossRate) + '%';

          return creditPosition;
        });

        this.setState({
          creditPositions,
        });
      },
      errCallback: err => {
        console.log(err);
      },
    });
  };

  render() {
    let { visible, renderItemWithTips } = this.props;
    if (!visible) return null;

    let { creditExchange, creditPositions } = this.state;

    return (
      <ScrollView
        style={{
          flex: 1,
          backgroundColor: getColors().base_oc_10,
        }}
        contentContainerStyle={{
          backgroundColor: getColors().base_oc_10,
        }}
      >
        <ExchangeInfo
          data={creditExchange}
          renderItemWithTips={renderItemWithTips}
        />
        <Positions data={creditPositions} />
        <Nomore />
      </ScrollView>
    );
  }
}

class OptionExchange extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    this._loadData();
  }

  _loadData = () => {
    this._fetchCustomerOptionExchange();
    this._fetchCustomerOptionPositions();
  };

  // 获取客户期权交易信息
  _fetchCustomerOptionExchange = () => {
    let { customerId, fetchData } = this.props;

    const data = { customerId };
    fetchData({
      path: api.customerOptionExchange,
      method: 'post',
      body: {
        data,
      },
      callback: res => {
        let optionExchange = [];
        let assetTotal = get(res, 'assetTotal', 0);
        optionExchange.push({
          name: '总资产',
          value: ConvertUtils.convertNumToStrWithUnitConversion(assetTotal),
        });

        let profitLoss = get(res, 'profitLoss', 0);
        optionExchange.push({
          name: '浮动盈亏',
          value: ConvertUtils.convertNumToStrWithUnitConversion(profitLoss),
        });

        let capitalMoney = get(res, 'capitalMoney', 0);
        optionExchange.push({
          name: '可用资产',
          value: ConvertUtils.convertNumToStrWithUnitConversion(capitalMoney),
        });

        let marketValueTotal = get(res, 'marketValueTotal', 0);
        optionExchange.push({
          name: '流通市值',
          value: ConvertUtils.convertNumToStrWithUnitConversion(
            marketValueTotal
          ),
        });

        // let assetAvailable = get(res, 'assetAvailable', 0);
        // optionExchange.push({
        //   name: '可用资金',
        //   value: ConvertUtils.convertNumToStrWithUnitConversion(assetAvailable),
        // });

        // let risk = get(res, 'risk', 0);
        // optionExchange.push({
        //   name: '风险度',
        //   value: ConvertUtils.convertNumToStrWithUnitConversion(risk),
        // });

        // let depositAvailable = get(res, 'depositAvailable', 0);
        // optionExchange.push({
        //   name: '可用保证金',
        //   value: ConvertUtils.convertNumToStrWithUnitConversion(
        //     depositAvailable
        //   ),
        // });

        // let depositBlock = get(res, 'depositBlock', 0);
        // optionExchange.push({
        //   name: '占用保证金',
        //   value: ConvertUtils.convertNumToStrWithUnitConversion(depositBlock),
        // });

        this.setState({
          optionExchange,
        });
      },
      errCallback: err => {
        console.log(err);
      },
    });
  };

  // 获取客户期权交易持仓信息
  _fetchCustomerOptionPositions = () => {
    let { customerId, fetchData } = this.props;

    const data = { customerId };
    fetchData({
      path: api.customerOptionPositions,
      method: 'post',
      body: {
        data,
      },
      callback: res => {
        let items = get(res, 'items', []);
        let optionPositions = map(items, item => {
          let optionPosition = {
            name: get(item, 'name', ''),
            contract: get(item, 'contract', ''),
            type: get(item, 'type', '') === 'C' ? '认购' : '认沽',
            direction: get(item, 'direction', ''),
            hold: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'hold', 0)
            ),
            marketValue: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'marketValueTotal', 0)
            ),
            cost: ConvertUtils.convertNumToStrWithUnitConversion(
              get(item, 'cost', 0)
            ),
          };

          let profitLoss = ConvertUtils.convertNumToStrWithUnitConversion(
            get(item, 'profitLoss', 0)
          );

          optionPosition.profitLoss = ConvertUtils.convertNumToStrWithSignSymbol(
            profitLoss
          );

          return optionPosition;
        });

        this.setState({
          optionPositions,
        });
      },
      errCallback: err => {
        console.log(err);
      },
    });
  };

  render() {
    let { visible, renderItemWithTips } = this.props;
    if (!visible) return null;

    let { optionExchange, optionPositions } = this.state;

    return (
      <ScrollView
        style={{
          flex: 1,
          backgroundColor: getColors().base_oc_10,
        }}
        contentContainerStyle={{
          backgroundColor: getColors().base_oc_10,
        }}
      >
        <ExchangeInfo
          data={optionExchange}
          renderItemWithTips={renderItemWithTips}
        />
        <OptionPositions data={optionPositions} />
        <Nomore />
      </ScrollView>
    );
  }
}

class OtcExchange extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      otcPositions: [],
    };
  }

  componentDidMount() {
    this._loadData();
  }

  _loadData = () => {
    this._fetchCustomerOtcPositions();
  };

  // 获取客户期权交易持仓信息
  _fetchCustomerOtcPositions = () => {
    let { customerId, fetchData } = this.props;

    const data = { customerId };
    fetchData({
      path: api.customerOtcPositions,
      method: 'post',
      body: {
        data,
      },
      callback: res => {
        let otcPositions = get(res, 'items', []);

        this.setState({
          otcPositions,
        });
      },
      errCallback: err => {
        console.log(err);
      },
    });
  };

  _renderOtcItems = () => {
    let { otcPositions } = this.state;
    return map(otcPositions, (item, index) => (
      <View
        key={index}
        style={{
          alignSelf: 'stretch',
          paddingHorizontal: 16,
          paddingVertical: 18,
          backgroundColor: getColors().base_oc_11,
          marginTop: 8,
        }}
      >
        <View style={{ alignSelf: 'stretch', flexDirection: 'row' }}>
          <Image source={ic_shares} style={{ width: 16, height: 16 }} />
          <Text
            style={{
              marginLeft: 5,
              fontSize: 15,
              color: getColors().base_fc_5,
            }}
          >
            {item.name + `（${item.code}）`}
          </Text>
        </View>
        <View
          style={{
            flexDirection: 'row',
            flexWrap: 'wrap',
            alignSelf: 'stretch',
            justifyContent: 'space-between',
            marginTop: 7,
          }}
        >
          {this._renderOtcDetails(item.details)}
        </View>
      </View>
    ));
  };

  _renderOtcDetails = items => {
    return map(items, (item, index) => {
      let color = getColors().base_fc_5;
      let value = ConvertUtils.convertNumToStrWithUnitConversion(item.value);
      if (item.emphasize) {
        value = ConvertUtils.convertNumToStrWithSignSymbol(value);
        color =
          (value.indexOf('+') !== -1 && getColors().base_fc_1) ||
          (value.indexOf('-') !== -1 && getColors().base_fc_3) ||
          color;
      }

      return (
        <View
          key={index}
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            width: 150 * widthScale,
            marginTop: 10,
          }}
        >
          <Text
            style={{
              fontSize: 15,
              color: getColors().base_fc_5,
            }}
          >
            {item.name}
          </Text>
          <Text
            style={{
              fontSize: 15,
              color,
            }}
          >
            {value}
          </Text>
        </View>
      );
    });
  };

  render() {
    let { visible } = this.props;
    if (!visible) return null;

    return (
      <ScrollView
        style={{
          flex: 1,
          backgroundColor: getColors().base_oc_10,
        }}
        contentContainerStyle={{
          backgroundColor: getColors().base_oc_10,
        }}
      >
        {this._renderOtcItems()}
        <Nomore />
      </ScrollView>
    );
  }
}

class Detail extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      active: 1,
    };
  }

  handleChangeActive(active) {
    this.setState({
      active,
    });
  }

  _renderTab = (name, index) => (
    <TouchableOpacity
      style={{
        flex: 1,
        alignSelf: 'stretch',
        justifyContent: 'center',
        alignItems: 'center',
      }}
      onPress={this.handleChangeActive.bind(this, index)}
    >
      <Text
        style={{
          fontSize: 15,
          color:
            this.state.active === index
              ? getColors().base_fc_2
              : getColors().base_fc_5,
        }}
      >
        {name}
      </Text>
    </TouchableOpacity>
  );

  _renderHead = () => {
    let {
      normalExchageActive,
      creditExchageActive,
      optionExchageActive,
      otcExchageActive,
    } = this.props;

    return (
      <View
        flexDirection="row"
        style={{
          flexDirection: 'row',
          height: 44,
          borderBottomColor: getColors().base_lc_1,
          borderBottomWidth: 1,
          paddingHorizontal: 16,
        }}
      >
        {normalExchageActive && this._renderTab('普通交易', 1)}
        {creditExchageActive && this._renderTab('信用交易', 2)}
        {optionExchageActive && this._renderTab('期权交易', 3)}
        {otcExchageActive && this._renderTab('基金理财', 4)}
      </View>
    );
  };

  render() {
    let {
      visible,
      customerId,
      fetchData,
      normalExchageActive,
      creditExchageActive,
      optionExchageActive,
      otcExchageActive,
      renderItemWithTips,
    } = this.props;
    if (!visible) return null;

    let { active } = this.state;
    return (
      <View
        style={{
          flex: 1,
          alignSelf: 'stretch',
          backgroundColor: getColors().base_oc_11,
        }}
      >
        {this._renderHead()}
        {normalExchageActive && (
          <NormalExchange
            visible={active === 1}
            customerId={customerId}
            fetchData={fetchData}
            renderItemWithTips={renderItemWithTips}
          />
        )}
        {creditExchageActive && (
          <CreditExchange
            visible={active === 2}
            customerId={customerId}
            fetchData={fetchData}
            renderItemWithTips={renderItemWithTips}
          />
        )}
        {optionExchageActive && (
          <OptionExchange
            visible={active === 3}
            customerId={customerId}
            fetchData={fetchData}
            renderItemWithTips={renderItemWithTips}
          />
        )}
        {otcExchageActive && (
          <OtcExchange
            visible={active === 4}
            customerId={customerId}
            fetchData={fetchData}
          />
        )}
      </View>
    );
  }
}

class CustomerDetailContainer extends Component {
  constructor(props) {
    super(props);

    let { getParam } = props.navigation;
    this.state = {
      active: 1,
      customerId: getParam('customerId', ''),
      customerInfo: {},
    };
  }

  componentDidMount() {
    // 如果是路由首页，则需要在此让过渡动画消失
    const key = get(this, ['props', 'navigation', 'state', 'key'], 'key');
    const routeName = get(
      this,
      ['props', 'navigation', 'state', 'routeName'],
      'routeName'
    );
    key === routeName && LoadingProgramModule.hide();

    this._loadData();
  }

  _loadData = () => {
    this._fetchCustomerInfo();
  };

  // 获取客户基本信息
  _fetchCustomerInfo = () => {
    let { fetchData } = this.props;
    let { customerId } = this.state;

    const data = { customerId };
    fetchData({
      path: api.customerInfo,
      method: 'post',
      body: {
        data,
      },
      callback: res => {
        let customerInfo = { ...res };
        this.setState({
          customerInfo,
        });
      },
      errCallback: err => {
        console.log(err);
      },
    });
  };

  handleChangeActive(active) {
    this.setState({
      active,
    });
  }

  _renderTab = (name, index) => (
    <TouchableOpacity
      style={{
        flex: 1,
        alignSelf: 'stretch',
        justifyContent: 'center',
        alignItems: 'center',
        borderBottomColor:
          this.state.active === index ? getColors().base_oc_27 : 'transparent',
        borderBottomWidth: 2,
      }}
      onPress={this.handleChangeActive.bind(this, index)}
    >
      <Text
        style={{
          fontSize: 15,
          color:
            this.state.active === index
              ? getColors().base_fc_2
              : getColors().base_fc_5,
          lineHeight: 44,
        }}
      >
        {name}
      </Text>
    </TouchableOpacity>
  );

  // 佣金率提示信息
  _renderAlert = (title, content) => {
    this.props.toggleOverlayContainer({
      visible: true,
      componentCreator: onCloseHandler => {
        return (
          <View
            style={{
              flex: 1,
              justifyContent: 'center',
              alignItems: 'center',
            }}
          >
            <DialogAlert
              title={title}
              content={content}
              type={'single'}
              firstBtnTitle={'确定'}
              onFirstBtnPress={() => {
                onCloseHandler && onCloseHandler();
              }}
            />
          </View>
        );
      },
    });
  };

  _renderItemWithTips = name => {
    const commissionText = 'A股本年普通交易的平均佣金率';
    if (name && name === '佣金率') {
      return (
        <TouchableOpacity
          style={{
            flexDirection: 'row',
            alignItems: 'center',
          }}
          onPress={() => this._renderAlert('佣金率', commissionText)}
        >
          <Text
            style={{
              fontSize: scaleSizeFont(15),
              color: getColors().base_fc_5,
              marginRight: 2,
            }}
          >
            {name}
          </Text>
          <Image
            source={ic_tips}
            style={{
              height: scaleSizeW(15),
              resizeMode: 'contain',
            }}
          />
        </TouchableOpacity>
      );
    }
    return (
      <Text
        style={{
          fontSize: scaleSizeFont(15),
          color: getColors().base_fc_5,
        }}
      >
        {name}
      </Text>
    );
  };

  render() {
    let { toggleErrorInfo, navigation } = this.props;
    let { active, customerId, customerInfo } = this.state;
    let normalExchageActive = get(customerInfo, 'normalExchageActive', false);
    let creditExchageActive = get(customerInfo, 'creditExchageActive', false);
    let optionExchageActive = get(customerInfo, 'optionExchageActive', false);
    let otcExchageActive = get(customerInfo, 'otcExchageActive', false);
    let showDetailTab =
      normalExchageActive ||
      creditExchageActive ||
      optionExchageActive ||
      otcExchageActive;

    return (
      <SafeAreaView style={styles.container}>
        <Top customerInfo={customerInfo} toggleErrorInfo={toggleErrorInfo} />
        <View
          style={{
            marginTop: 8,
            height: 44,
            backgroundColor: getColors().base_fc_8,
            borderBottomWidth: 1,
            borderBottomColor: getColors().base_lc_1,
            flexDirection: 'row',
          }}
        >
          {this._renderTab('概览', 1)}
          {showDetailTab && this._renderTab('明细', 2)}
        </View>
        <Overview
          visible={active === 1}
          navigate={navigation.navigate}
          fetchData={this.props.fetchData}
          customerId={this.state.customerId}
          customerInfo={customerInfo}
          renderItemWithTips={this._renderItemWithTips}
        />
        {showDetailTab && (
          <Detail
            visible={active === 2}
            customerId={customerId}
            normalExchageActive={normalExchageActive}
            creditExchageActive={creditExchageActive}
            optionExchageActive={optionExchageActive}
            otcExchageActive={otcExchageActive}
            fetchData={this.props.fetchData}
            renderItemWithTips={this._renderItemWithTips}
          />
        )}
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: getColors().base_oc_11,
  },
});

const mapDispatchToProps = dispatch => {
  return bindActionCreators(
    {
      fetchData,
      toggleErrorInfo,
      toggleOverlayContainer,
    },
    dispatch
  );
};

export default connect(
  null,
  mapDispatchToProps
)(CustomerDetailContainer);
